<?php

    class News extends ActiveRecord {
        var $_custom_fields = array(); // holds cutom fields AR objects

        function _setup()
        {
            $this->table = DB_PREFIX.'news';
        }
        
        function validate()
        {
            $this->validates_presence_of('title');
        }
        
        function after_validation()
        {
            $this->kill_xss();
            // index name
            $index_name = $this->get('index_name');
            if ( empty($index_name) )  {
                $this->set('index_name', $this->create_index_name($this->get('title')));
            } else {
                $this->set('index_name', $this->create_index_name($index_name)); // just to make sure its unique
            }
            // publish date
            $publish_date = $this->get('publish_date');
            if ( empty($publish_date) )
            {
                $this->set('publish_date',DB_DATESTAMP);
            }
            
            // safehtml strips out html comments
            // for the breaks
            $htmlcontent = $this->get('content');
            
            // replace quotes in the text
            $htmlcontent = string_replace_quotes($htmlcontent,true);            
            
            if(empty($htmlcontent)) return;
            require VENDOR.'/htmlpurifier/HTMLPurifier.auto.php';
            $config = HTMLPurifier_Config::createDefault();
            $config->set('Core', 'Encoding', DEFAULT_CHARSET); //replace with your encoding
            $config->set('HTML','Doctype',HTML_DOCTYPE);
            $purifier = new HTMLPurifier($config);

            $clean_html = $purifier->purify($this->get('content'));
            $this->set('content',$cleanedhtml);        
            
        }
        
        function kill_xss()
        {
            // clean out any potentially bad xss
            include_once VENDOR.'/safehtml/safehtml.php';
            $safe =& new safehtml();
            foreach(array('meta_keywords','meta_description','title','source') as $field)
            {
                $content = '';
                $content = $this->get($field);
                $cleanedhtml = $safe->parse($content);
                $this->set($field,strip_tags($cleanedhtml)) ;
                $safe->clear();
            }
        }
        
        function after_validation_on_create()
        {
            $this->set('id',$this->db->Insert_ID());
            $this->write_categories();
            # create new entry in the search_index table, put in url and write the search_index_id to this row
            use_model('search_index');
            $index = new Search_Index();
            $index->set('url', get_installed_path().'/news/read/'.$this->get('index_name'));
            if ( $title = $this->get('meta_title') )
            {
                $index->set('title',$title);
            } else {
                $index->set('title',$this->get('title'));
            }
            $content = $index->prepare_content_for_search_index($this->get('content'));
            $index->set('content',$content);
            $index->save();
            $this->set('search_index_id',$index->get('id'));
            $this->save();
        }
        
        function after_validation_before_create()
        {
            $this->set('user_id',$_SESSION['user_id']);
        }
        
        function after_validation_on_update()
        {
            $this->write_categories();
            # need to update URL, title/meta title in the search_index
            use_model('search_index');
            $index = new Search_Index();
            if ( $index->load($this->get('search_index_id')) )
            {
                $index->set('url','/news/read/'.$this->get('index_name'));
                if ( $title = $this->get('meta_title') )
                {
                    $index->set('title',$title);
                } else {
                    $index->set('title',$this->get('title'));
                }
                $content = $index->prepare_content_for_search_index($this->get('content'));
                $index->set('content',$content);
                $index->save();
            } else { // no index was made ever?
                $index->set('url', get_installed_path().'/news/read/'.$this->get('index_name'));
                if ( $title = $this->get('meta_title') )
                {
                    $index->set('title',$title);
                } else {
                    $index->set('title',$this->get('title'));
                }
                $content = $index->prepare_content_for_search_index($this->get('content'));
                $index->set('content',$content);
                $index->save();
                $this->set('search_index_id',$index->get('id'));
                $this->save();
            }
        }
        
        function write_categories()
        {
            $cats = $this->get('categories');
            if ( empty($cats) )
            {
                $cats = array(1); // put it in default category
            }
            // delete all old joins then add new
            $this->db->Execute('DELETE FROM `'.DB_PREFIX.'categories_news` WHERE news_id=?',array($this->get('id')));
            foreach( $cats as $c )
            {
                $this->db->Execute("INSERT INTO `".DB_PREFIX."categories_news` (news_category_id,news_id) values (?,?)",
                                 array($c,$this->get('id')));
            }
        }
        
        function &recent_stories_paged()
        {
            // get array pieces instead of table
            $sql = "SELECT 
                      id, index_name, file_id, title, source, content, publish_date, id `Categories`
                    FROM
                      `{$this->table}`
                    WHERE status = 1
                    ORDER BY publish_date desc";
            $pager = $this->pager($sql);
            $pager->escape_html = false;
            $pager->rs_callback = array($this,'pager_row_process');
            return $pager;
        }
        
        function &get_stories_by_category($category)
        {
            use_model('news_categories');
            $nc = new News_Categories();
            $cat_id = $nc->find_rows(array(
                                    'search'=>'first',
                                    'conditions'=>array('index_name=?',$category)
                                    ));
            if ( $cat_id['id'] )
            {
                $sql = "SELECT 
                          n.*, n.id `Categories`, nc.name `Category Name`
                        FROM
                          `{$this->table}` n, `".DB_PREFIX."categories_news` c, `".DB_PREFIX."news_categories` nc
                        WHERE
                          c.news_category_id = {$cat_id['id']} 
                        AND
                          nc.id = c.news_category_id
                        AND
                          n.id = c.news_id
                        AND
                         n.status != 0
                        ORDER BY n.publish_date DESC
                        ";
                $pager = $this->pager($sql);
                $pager->escape_html = false;
                $pager->rs_callback = array($this,'pager_row_process');
                return $pager;
            } else {
                return false;
            }
            
        }
        
        function &get_paged_news()
        {
            $sql = "SELECT 
                      id, publish_date `Date Published`, title `Title`, id `Categories`
                    FROM `{$this->table}` 
                    WHERE
                      status !=0
                    ORDER BY publish_date desc";
            $pager = $this->pager($sql);
            $pager->row_key = 'id';
            $pager->escape_html = false;
            $pager->rs_callback = array($this,'pager_row_process');
            return $pager;
        }
        
        function pager_row_process(&$f)
        {            
            if ( isset($f['Categories']) )
            {
                $c    = new News_Categories();
                $cats = $c->get_categories_by_news($f['Categories']);
                $cat_list = array();
                foreach( $cats as $key => $value )
                {
                    $cat_list[] = link_to($value,url_for(array('controller'=>'news' ,'action'=>'category/'.$key)));
                }
                $f['Categories'] = implode(', ',$cat_list);
            }            
            if( isset($f['Date Published']) ) {
                $f['Date Published'] = date_format($f['Date Published'], '%D %r');
            }            
        }
        
        function browse_by_month($month,$year)
        {
            $year  = sanitize($year);
            $month = sanitize($month);
            $counted = $this->db->GetOne("SELECT 
                                            count(id) 
                                          FROM `{$this->table}`
                                          WHERE 
                                            status != 0
                                          AND
                                            publish_date LIKE '$year-$month-%'");
            
            $sql = "SELECT 
                      id, publish_date `Date Published`, title `Title`, id `Categories` 
                    FROM `{$this->table}` 
                    WHERE 
                      status != 0
                    AND
                    publish_date LIKE '$year-$month-%' 
                    ORDER BY publish_date desc";
            $pager = $this->pager($sql);
            $pager->row_key = 'id';
            $pager->the_total_count = $counted;
            $pager->escape_html = false;
            $pager->rs_callback = array($this,'pager_row_process');
            return $pager;
        }
        
        function browse_by_date($year,$month)
        {
            if ( is_null($year) )
            {
                $year = date('Y');
            }
            if ( is_null($month) )
            {
                $month = date('m');
            }
            $year  = sanitize($year);
            $month = sanitize($month);
          
            $sql = "SELECT 
                      id, publish_date, title, index_name 
                    FROM `{$this->table}` 
                    WHERE 
                      status != 0
                    AND
                    publish_date LIKE '$year-$month-%' 
                    ORDER BY publish_date desc";
            $pager = $this->pager($sql);
            $pager->escape_html = false;
            $pager->rs_callback = array($this,'pager_row_process');
            return $pager;
        }
                
        function after_delete()
        {
            // delete all category joins
            $this->db->Execute("DELETE FROM `".DB_PREFIX."categories_news` WHERE news_id = ?",$this->get('id'));
            
            // delete the search index for it as well
            use_model('search_index');
            $index = new Search_Index();
            if ( $index->load($this->get('search_index_id')) )
            {
                $index->delete();
            }
        }
        
        // only works on loaded items to get its categories
        function selected_categories()
        {
            $cats = $this->db->GetCol("SELECT news_category_id FROM `".DB_PREFIX."categories_news` WHERE news_id=?",array($this->get('id')));
            if ( empty($cats) )
            {
                $cats = array(1);
            }
            return $cats;
        }
        
        function load_by_index_name($index_name,$published_only=true)
        {
            $status = '';
            if ( $published_only )
            {
                $status = 'AND status !=0';
            }
            
            return $this->load("index_name=? $status", array(rawurlencode($index_name)));            
        }
        
        function archives_list()
        {
            $sql = "SELECT 
                      count(id) as total,
                      date_format(publish_date, '%m') as publish_month,
                      date_format(publish_date, '%Y') as publish_year,
                      date_format(publish_date, '%M %Y') as publish_date_full
                    FROM 
                      `{$this->table}` 
                    GROUP BY publish_date_full 
                    ORDER BY publish_date DESC";
            return $this->db->GetAll($sql);
        }

		// get previous story
		function previous_story()
		{
			return $this->db->GetAll('SELECT 
										id,title,index_name
									  FROM
										`{$this->table}`
									  WHERE id < ?
									  AND status = 1
									  LIMIT 1',
									  array($this->get('id')));
		}
		
		// get next story
		function next_story()
		{
			return $this->db->GetAll('SELECT 
										id,title,index_name
									  FROM
										`{$this->table}`
									  WHERE id > ?
									  AND status = 1
									  LIMIT 1',
									  array($this->get('id')));
		}
		
		function &custom_fields()
        {
            if (!empty($this->_custom_fields)) {
                return $this->_custom_fields;
            }
            use_model('entries_custom_fields');
            $c = new entries_custom_fields();
            $cf = $c->find('news_id=?', array($this->get('id')));
            if ($cf) {
                $this->_custom_fields = $cf;
                return $cf;
            } else {
                return false;
            }
        }
        
        function &custom_field($field_key)
        {
            if (array_key_exists($field_key, $this->_custom_fields) 
                && is_object($this->_custom_fields[$field_key])) {
                return $this->_custom_fields[$field_key];
            }
            use_model('entries_custom_fields');
            $cfid = $this->db->GetOne('select id from custom_fields where field_key = ?', $field_key);
            if ($cfid) {
                $c = new entries_custom_fields();
                $cf = $c->find('news_id=? and custom_field_id=?', 
                                array($this->get('id'), $cfid));
                if ($cf) {
                    $this->_custom_fields[$field_key] = $cf;
                    return $cf;
                }
                return false;
            }
            return false;            
        }
        
        function &assoc_published()
        {
            return $this->db->GetAssoc('select index_name, title from  news where status=1 order by title');
        }
        
        function has_file()
        {
            $file_id = $this->get('file_id');
            if ($file_id) {
                return true;
            }
            return false;
        }
    }

?>